package com.gome.ocean.service.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gome.ocean.common.utils.AddressUtils;
import com.gome.ocean.service.task.CallBack;
import com.gome.ocean.service.task.CallBackTask;
import com.gome.ocean.service.thread.NamedThreadFactory;

/**
 * Cmd执行工具
 * 
 * @author haqiaolong 2016年1月25日 下午12:13:18
 * @since 5.0.0
 */
public final class CmdToolkit {

    private static final Logger    LOG              = LoggerFactory.getLogger(CmdToolkit.class);
    private static final String    CALL_BACK_THREAD = "call_back_thread";
    private static ExecutorService executorService  = Executors.newSingleThreadExecutor(new NamedThreadFactory(CALL_BACK_THREAD));

    private CmdToolkit(){
    }

    public static String executeCmd(final String cmd, final CallBack callBack) {
        StringBuffer cmdout = new StringBuffer();
        LOG.info("exec commond：" + cmd);
        InputStream input = null;
        BufferedReader reader = null;
        Process process = null;
        try {
            if (AddressUtils.isLinux()) {
                process = Runtime.getRuntime().exec(new String[] { "/bin/sh", "-c", cmd }); // 执行一个系统命令
            } else if (AddressUtils.isWindons()) {
                process = Runtime.getRuntime().exec(new String[] { "cmd", "/C", cmd }); // 执行一个系统命令
            } else {
                LOG.info("系统不支持命令！cmd=" + cmd);
                return StringUtils.EMPTY;
            }
            if (callBack != null) {
                executorService.submit(new CallBackTask(callBack, 5000));
            }
            input = process.getInputStream();
            reader = new BufferedReader(new InputStreamReader(input));
            String line = null;
            while ((line = reader.readLine()) != null) {
                cmdout.append(line).append("\r\n");
            }
            process.waitFor();
            process.destroy();
            LOG.info("执行系统命令后的结果为：\n" + cmdout.toString());
            return cmdout.toString();
        } catch (IOException | InterruptedException e) {
            LOG.error("任务执行失败！请检查！", e);
            e.printStackTrace();
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static String executeCmd(final String cmd) {
        return executeCmd(cmd, null);
    }
}
